from django.shortcuts import render,HttpResponseRedirect,HttpResponse
from app.forms.project import ProjectModelForm
from django.http import JsonResponse
from app import models
from utils import cos
import time
from django.conf import settings

def project_list(request):
    if request.method == 'GET':
        form = ProjectModelForm(request)
        project_dict = {'star':[],'my':[],"join":[]}
        myCreate = models.Project.objects.filter(creator=request.tracer.user)
        for item in myCreate:
            if item.star:
                project_dict['star'].append({'value':item,'type':'my'})
            else:
                project_dict['my'].append(item)
        myJoin = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in myJoin:
            if item.star:
                project_dict['star'].append({'value':item.project,'type':'join'})
            else:
                project_dict['join'].append(item)
        return render(request,'app/project_list.html',{'form':form,'project_dict':project_dict})
    else:
        form = ProjectModelForm(request, data=request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            #必须有后面的-1304189301
            bukect = f"{str(time.time()).replace('.','')}-{str(request.tracer.user.phone)}-1304189301"
            print('-->',bukect)
            cos.create_bucket(bukect)
            form.instance.creator = request.tracer.user
            form.instance.bucket = bukect
            form.instance.region = settings.COS_REGION
            instance = form.save()
            return JsonResponse({'status':True})
        return JsonResponse({'status':False,'error':form.errors})


def project_star(request,type,id):
    if request.method == 'GET':
        if type == 'my':
            models.Project.objects.filter(id=id,creator=request.tracer.user).update(star=True)
            return HttpResponseRedirect('/api/v1/project/list/')
        elif type == 'join':
            models.ProjectUser.objects.filter(project_id=id,user=request.tracer.user).update(star=True)
            return HttpResponseRedirect('/api/v1/project/list/')
        return HttpResponse('请求错误')

def project_unstar(request,type,id):
    if request.method == 'GET':
        """ 取消星标 """
        if type == 'my':
            models.Project.objects.filter(id=id, creator=request.tracer.user).update(star=False)
            return HttpResponseRedirect('/api/v1/project/list/')

        if type == 'join':
            models.ProjectUser.objects.filter(project_id=id, user=request.tracer.user).update(star=False)
            return HttpResponseRedirect('/api/v1/project/list/')

        return HttpResponse('请求错误')